/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package kimo.persistence.controllers;

import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import kimo.persistence.entities.Daok;
import kimo.persistence.entities.Pcheck;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import kimo.persistence.controllers.exceptions.NonexistentEntityException;
import kimo.persistence.entities.User;

/**
 *
 * @author a381u296
 */
public class UserJpaController implements Serializable {

    public UserJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(User user) {
        if (user.getPcheckList() == null) {
            user.setPcheckList(new ArrayList<Pcheck>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Daok userDaokCd = user.getUserDaokCd();
            if (userDaokCd != null) {
                userDaokCd = em.getReference(userDaokCd.getClass(), userDaokCd.getDaokCd());
                user.setUserDaokCd(userDaokCd);
            }
            List<Pcheck> attachedPcheckList = new ArrayList<Pcheck>();
            for (Pcheck pcheckListPcheckToAttach : user.getPcheckList()) {
                pcheckListPcheckToAttach = em.getReference(pcheckListPcheckToAttach.getClass(), pcheckListPcheckToAttach.getCheckId());
                attachedPcheckList.add(pcheckListPcheckToAttach);
            }
            user.setPcheckList(attachedPcheckList);
            em.persist(user);
            if (userDaokCd != null) {
                userDaokCd.getUserList().add(user);
                userDaokCd = em.merge(userDaokCd);
            }
            for (Pcheck pcheckListPcheck : user.getPcheckList()) {
                User oldCheckUserIdOfPcheckListPcheck = pcheckListPcheck.getCheckUserId();
                pcheckListPcheck.setCheckUserId(user);
                pcheckListPcheck = em.merge(pcheckListPcheck);
                if (oldCheckUserIdOfPcheckListPcheck != null) {
                    oldCheckUserIdOfPcheckListPcheck.getPcheckList().remove(pcheckListPcheck);
                    oldCheckUserIdOfPcheckListPcheck = em.merge(oldCheckUserIdOfPcheckListPcheck);
                }
            }
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(User user) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            User persistentUser = em.find(User.class, user.getUserId());
            Daok userDaokCdOld = persistentUser.getUserDaokCd();
            Daok userDaokCdNew = user.getUserDaokCd();
            List<Pcheck> pcheckListOld = persistentUser.getPcheckList();
            List<Pcheck> pcheckListNew = user.getPcheckList();
            if (userDaokCdNew != null) {
                userDaokCdNew = em.getReference(userDaokCdNew.getClass(), userDaokCdNew.getDaokCd());
                user.setUserDaokCd(userDaokCdNew);
            }
            List<Pcheck> attachedPcheckListNew = new ArrayList<Pcheck>();
            for (Pcheck pcheckListNewPcheckToAttach : pcheckListNew) {
                pcheckListNewPcheckToAttach = em.getReference(pcheckListNewPcheckToAttach.getClass(), pcheckListNewPcheckToAttach.getCheckId());
                attachedPcheckListNew.add(pcheckListNewPcheckToAttach);
            }
            pcheckListNew = attachedPcheckListNew;
            user.setPcheckList(pcheckListNew);
            user = em.merge(user);
            if (userDaokCdOld != null && !userDaokCdOld.equals(userDaokCdNew)) {
                userDaokCdOld.getUserList().remove(user);
                userDaokCdOld = em.merge(userDaokCdOld);
            }
            if (userDaokCdNew != null && !userDaokCdNew.equals(userDaokCdOld)) {
                userDaokCdNew.getUserList().add(user);
                userDaokCdNew = em.merge(userDaokCdNew);
            }
            for (Pcheck pcheckListOldPcheck : pcheckListOld) {
                if (!pcheckListNew.contains(pcheckListOldPcheck)) {
                    pcheckListOldPcheck.setCheckUserId(null);
                    pcheckListOldPcheck = em.merge(pcheckListOldPcheck);
                }
            }
            for (Pcheck pcheckListNewPcheck : pcheckListNew) {
                if (!pcheckListOld.contains(pcheckListNewPcheck)) {
                    User oldCheckUserIdOfPcheckListNewPcheck = pcheckListNewPcheck.getCheckUserId();
                    pcheckListNewPcheck.setCheckUserId(user);
                    pcheckListNewPcheck = em.merge(pcheckListNewPcheck);
                    if (oldCheckUserIdOfPcheckListNewPcheck != null && !oldCheckUserIdOfPcheckListNewPcheck.equals(user)) {
                        oldCheckUserIdOfPcheckListNewPcheck.getPcheckList().remove(pcheckListNewPcheck);
                        oldCheckUserIdOfPcheckListNewPcheck = em.merge(oldCheckUserIdOfPcheckListNewPcheck);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = user.getUserId();
                if (findUser(id) == null) {
                    throw new NonexistentEntityException("The user with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            User user;
            try {
                user = em.getReference(User.class, id);
                user.getUserId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The user with id " + id + " no longer exists.", enfe);
            }
            Daok userDaokCd = user.getUserDaokCd();
            if (userDaokCd != null) {
                userDaokCd.getUserList().remove(user);
                userDaokCd = em.merge(userDaokCd);
            }
            List<Pcheck> pcheckList = user.getPcheckList();
            for (Pcheck pcheckListPcheck : pcheckList) {
                pcheckListPcheck.setCheckUserId(null);
                pcheckListPcheck = em.merge(pcheckListPcheck);
            }
            em.remove(user);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<User> findUserEntities() {
        return findUserEntities(true, -1, -1);
    }

    public List<User> findUserEntities(int maxResults, int firstResult) {
        return findUserEntities(false, maxResults, firstResult);
    }

    private List<User> findUserEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(User.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public User findUser(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(User.class, id);
        } finally {
            em.close();
        }
    }

    public int getUserCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<User> rt = cq.from(User.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
